import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

public class consumerThead {

    private final static String QUEUE_NAME = "queue_A";

    public static Channel getFactory() {
        //创建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        //channel 实现了自动 close 接口 自动关闭 不需要显示关闭
        try {
            Connection connection = factory.newConnection(); // 创建一个链接
            Channel channel = connection.createChannel();  // 创建一个通道
            return channel;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] args) throws IOException {

        Channel channel = getFactory();
        // 工作线程
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String receivedMessage = new String(delivery.getBody());
            try {
                Random random = new Random();
                int t = random.nextInt(10) * 500;
                System.out.println("时间： " + t);
                Thread.sleep(t);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接收到消息:" + receivedMessage);
            // 标记tag，手动单条应答
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            // 设置qos 数量
            channel.basicQos(2);
        };
        System.out.println("C2 消费者启动等待消费......");
        // 手动应答
        boolean autoAck = false;
        channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, (consumerTag) -> {
            System.out.println(consumerTag + "消费者取消消费接口回调逻辑");
        });
    }



}
